package com.css.fxfzdzzh.zcpt.sys.controller;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzdzzh.base.response.RestResponse;
import com.css.fxfzdzzh.constants.FxfzConstants;
import com.css.fxfzdzzh.util.CreateGson;
import com.css.fxfzdzzh.util.ResponseCreator;
import com.css.fxfzdzzh.zcpt.sys.entity.vo.AreaVO;
import com.css.fxfzdzzh.zcpt.sys.service.SysAreaService;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Dbj
 * @date 2022年08月10日  11:17
 */
@RestController
@RequestMapping("/fxfz/sArea")
@Slf4j
public class SysAreaController {
    @Autowired
    private SysAreaService sysAreaService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    /**
     * 获取区域树
     */
    @GetMapping("/jsonSAreaTree")
    public RestResponse jsonSAreaTree(@RequestParam("divisionId") String divisionId) {
        RestResponse restResponse = null;
        try{
            String jsonStr = sysAreaService.jsonSAreaTree(divisionId);
            Gson gson = CreateGson.createGson();
            List sysMenuList = gson.fromJson(jsonStr, List.class);
            restResponse = RestResponse.succeed(sysMenuList);
        }catch (Exception e){
            log.error("查询区域失败!",e);
            restResponse = RestResponse.fail("查询区域失败!");
        }
        return restResponse;
    }

    /**
     * 获取区域树
     */
    @GetMapping("/jsonSAreaTree2")
    public RestResponse jsonSAreaTree2(@RequestParam("divisionId") String divisionId) {
        RestResponse restResponse = null;
        try{
            String jsonStr = sysAreaService.jsonSAreaTree(divisionId);
            Gson gson = CreateGson.createGson();
            List sysMenuList = gson.fromJson(jsonStr, List.class);
            if("1".equals(divisionId)){
               for(Object obj : sysMenuList){
                   LinkedTreeMap map = (LinkedTreeMap) obj;
                   String name = map.get("name").toString();
                   String id = map.get("id").toString();
                   if("北京市".equals(name) || "上海市".equals(name) || "天津市".equals(name) || "重庆市".equals(name)){
                       String json = sysAreaService.getChildAreaById(id);
                       List list = gson.fromJson(json, List.class);
                       LinkedTreeMap temp =(LinkedTreeMap) list.get(0);
                       map.put("id",temp.get("id").toString());
                       map.put("value",temp.get("name").toString());
                       map.put("name",temp.get("name").toString());
                   }
               }
            }
            restResponse = RestResponse.succeed(sysMenuList);
        }catch (Exception e){
            log.error("查询区域失败!",e);
            restResponse = RestResponse.fail("查询区域失败!");
        }
        return restResponse;
    }

    /**
     * 根据上级区域获取下级区域
     */
    @GetMapping("/getChildAreaById")
    public RestResponse getChildAreaById(@RequestParam("divisionId") String divisionId) {
        RestResponse restResponse = null;
        try{
            String jsonStr = sysAreaService.getChildAreaById(divisionId);
            Gson gson = CreateGson.createGson();
            List sysMenuList = gson.fromJson(jsonStr, List.class);
            restResponse = RestResponse.succeed(sysMenuList);
        }catch (Exception e){
            log.error("查询区域失败!",e);
            restResponse = RestResponse.fail("查询区域失败!");
        }
        return restResponse;
    }

    /**
     * 获取所有的区域code
     */
    @GetMapping("/getAllDivisionCode")
    public RestResponse getAllDivisionCode() {
        Gson gson = CreateGson.createGson();
        RestResponse restResponse = null;
        try{
            List sysAreaList = sysAreaService.getAllDivisionCode();
            restResponse = RestResponse.succeed(sysAreaList);
        }catch (Exception e){
            log.error("查询区域编码失败!",e);
            restResponse = RestResponse.fail("查询区域编码失败!");
        }
        return restResponse;
    }

    /**
     * 获取区域code
     */
    @GetMapping("/getDivisionCodeById")
    public RestResponse getDivisionCodeById(@RequestParam("divisionId") String divisionId) {
        Gson gson = CreateGson.createGson();
        RestResponse restResponse = null;
        try{
            String areaId = sysAreaService.getDivisionCodeById(divisionId);
            areaId =(String) JSONObject.parse(areaId);
            restResponse = RestResponse.succeed(areaId);
        }catch (Exception e){
            log.error("查询区域编码失败!",e);
            restResponse = RestResponse.fail("查询区域编码失败!");
        }
        return restResponse;
    }

    /**
     * 根据省市县名称查询id用于app端在地图上创建数据时保存id的情况
     */
    @GetMapping("/getIdByCondition")
    public RestResponse getIdByCondition(@RequestParam("province") String province,@RequestParam("city") String city,
                                         @RequestParam("area") String area) {
        Gson gson = CreateGson.createGson();
        RestResponse restResponse = null;
        try{
            province = URLEncoder.encode(province,"UTF-8");
            city = URLEncoder.encode(city,"UTF-8");
            area = URLEncoder.encode(area,"UTF-8");
            String jsonStr = sysAreaService.getIdByCondition(province,city,area);
            restResponse = RestResponse.succeed(jsonStr);
        }catch (Exception e){
            log.error("查询区域编码失败!",e);
            restResponse = RestResponse.fail("查询区域编码失败!");
        }
        return restResponse;
    }

    @GetMapping("/getAreaTree")
    public RestResponse getAreaTree() {
        RestResponse restResponse = null;
        Gson gson = CreateGson.createGson();
        String jsonStr = redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  + "areaList");
        jsonStr =(String) JSONObject.parse(jsonStr);
        List sysAreaList = gson.fromJson(jsonStr, List.class);
        List<AreaVO> children =new ArrayList<>();
        if(sysAreaList!=null && sysAreaList.size()>0){
            for(int i=0;i<sysAreaList.size();i++){
                LinkedTreeMap map =(LinkedTreeMap)  sysAreaList.get(i);
                String name = map.get("name").toString();
                if(name.equals("北京市") || name.equals("天津市") || name.equals("上海市") || name.equals("重庆市") ){
                    if(map.get("divisionLevel").equals("2")){
                        AreaVO vo = new AreaVO();
                        vo.setId(map.get("uuid").toString());
                        vo.setPid(map.get("parentId").toString());
                        vo.setName(map.get("name").toString());
                        vo.setCode(map.get("code").toString());
                        vo.setArea(map.get("area")==null?new BigDecimal(0) :new BigDecimal(map.get("area").toString()));
                        free(map.get("uuid").toString(),sysAreaList,vo);
                        children.add(vo);
                    }
                }else if(map.get("divisionLevel").equals("1")){
                    AreaVO vo = new AreaVO();
                    vo.setId(map.get("uuid").toString());
                    vo.setPid(map.get("parentId").toString());
                    vo.setName(map.get("name").toString());
                    vo.setCode(map.get("code").toString());
                    vo.setArea(map.get("area")==null?new BigDecimal(0) :new BigDecimal(map.get("area").toString()));
                    free(map.get("uuid").toString(),sysAreaList,vo);
                    children.add(vo);
                }
            }
        }
        String s = CreateGson.createGson().toJson(children);

        return ResponseCreator.createSuccessResponse(s);
    }

    void free(String id,List trees,AreaVO root){
        List<AreaVO> children =new ArrayList<>();
        for (int i =0; i < trees.size(); i++) {
            LinkedTreeMap map = (LinkedTreeMap) trees.get(i);
            if (map.get("parentId").equals(id)) {
                if("北京市".equals(map.get("name").toString())){
                    System.out.println("---");
                }
                AreaVO root1 = new AreaVO();
                root1.setId(map.get("uuid").toString());
                root1.setPid(map.get("parentId").toString());
                root1.setName(map.get("name").toString());
                root1.setCode(map.get("code").toString());
                root1.setArea(map.get("area")==null?new BigDecimal(0) :new BigDecimal(map.get("area").toString()));
                String divisionLevel = map.get("divisionLevel").toString();
                if("3".equals(divisionLevel)){
                    children.add(root1);
                    //leaf=2;
                }else{
                    free(root1.getId(), trees, root1);
                    children.add(root1);
                }
            }
        }
        root.setChildren(children);
    }

    /**
     * 根据区域id获取区域名称，可传递单个id，也可通过英文逗号将多个id拼成字符串
     */
    @GetMapping("/getAreaNameByAreaId")
    public RestResponse getAreaNameByAreaId(@RequestParam("areaId") String areaId){
        if("".equals(areaId)){
            return ResponseCreator.createSuccessResponse("");
        }
        String areaName = sysAreaService.getAreaNameByAreaId(areaId);
        return ResponseCreator.createSuccessResponse(areaName);
    }

    /**
     * 根据区域id获取区域名称，可传递单个id，也可通过英文逗号将多个id拼成字符串
     */
    @GetMapping("/getSysAreaByName")
    public RestResponse getSysAreaByName(@RequestParam("province") String province,@RequestParam("city") String city,
                                         @RequestParam("area") String area){
        if("".equals(province)){
            return ResponseCreator.createSuccessResponse("");
        }
        String areaName = sysAreaService.getSysAreaByName(province,city,area);
        return ResponseCreator.createSuccessResponse(areaName);
    }

}
